package com.handpay.nocardpay.baselibrary.account.view.fragment;


import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.handpay.nocardpay.baselibrary.DelegateActivity;
import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.account.model.bean.Account;
import com.handpay.nocardpay.baselibrary.account.model.bean.VerificationCodeBean;
import com.handpay.nocardpay.baselibrary.account.presenter.AccountPresenterImpl;
import com.handpay.nocardpay.baselibrary.account.presenter.VerfcodePresenterImpl;
import com.handpay.nocardpay.baselibrary.account.view.ILoginView;
import com.handpay.nocardpay.baselibrary.account.view.ISendVerfCodeView;
import com.handpay.nocardpay.baselibrary.account.view.IShowHideFragmentListener;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.permission.PermissionRequest;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;
import com.handpay.nocardpay.baselibrary.utils.PreferenceManager;
import com.handpay.nocardpay.baselibrary.utils.StatusBarUtil;
import com.j256.ormlite.field.types.NativeUuidType;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.util.HashMap;
import java.util.List;

import static com.handpay.nocardpay.baselibrary.permission.PermissionCode.REQUEST_CODE_SETTING;

/**
 * @author sxshi
 */
public class NoCardLoginFragment extends BaseFragment implements ILoginView, ISendVerfCodeView, PermissionRequest.onPermissionRequestCallBack {

    private EditText et_phone;
    private EditText et_verfcode;

    private Button btn_login;
    private TextView mGetVerfcode;
    private TextView mFastBillLogin;

    private HashMap<String, Object> paramers;
    private AccountPresenterImpl mLognLoginPresenter;
    private VerfcodePresenterImpl verfcodePresenter;
    private PermissionRequest perssionRequest;

    private String phone, verfcode;

    private CountDownTimer mCountDownTimer;
    private IShowHideFragmentListener showHideFragmentListener;

    public void setShowHideFragmentListener(IShowHideFragmentListener showHideFragmentListener) {
        this.showHideFragmentListener = showHideFragmentListener;
    }

    public static NoCardLoginFragment newInstance() {
        Bundle args = new Bundle();
        NoCardLoginFragment fragment = new NoCardLoginFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_nocardpaylogin;
    }

    @Override
    public void initView(View view) {
        et_phone = (EditText) view.findViewById(R.id.et_phone);
        et_verfcode = (EditText) view.findViewById(R.id.et_verfcode);
        btn_login = (Button) view.findViewById(R.id.btn_login);
        mGetVerfcode = (TextView) view.findViewById(R.id.btn_getcode);
        mFastBillLogin = (TextView) view.findViewById(R.id.btn_fastlogin);
    }

    @Override
    public void setStatusBar(View view) {
        super.setStatusBar(view);
        StatusBarUtil.setTranslucentForImageViewInFragment(_mActivity, 0, null);
    }

    @Override
    public void initListener() {
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideSoftInput();
                phone = et_phone.getText().toString();
                verfcode = et_verfcode.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    DialogUtils.showToast(getActivity(), _mActivity.getString(R.string.hint_no_card_pay_please_input_phone_no));
                    return;
                }
                if (!CommonUtils.isMobileNum(phone)) {
                    DialogUtils.showToast(getActivity(), _mActivity.getString(R.string.input_right_phone_tip));
                    return;
                }

                if (TextUtils.isEmpty(verfcode)) {
                    DialogUtils.showToast(getActivity(), _mActivity.getString(R.string.verfcode));
                    return;
                }
                perssionRequest.requestPermission(Permission.PHONE, Permission.STORAGE);
            }
        });

        mGetVerfcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSoftInput();
                phone = et_phone.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.tip), _mActivity.getString(R.string.hint_no_card_pay_please_input_phone_no), false);
                    return;
                }
                if (!CommonUtils.isMobileNum(phone)) {
                    DialogUtils.showToast(getActivity(), _mActivity.getString(R.string.input_right_phone_tip));
                    return;
                }
                mGetVerfcode.setEnabled(false);
                mCountDownTimer.start();
                sendVerCode();
            }
        });

        mFastBillLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showHideFragmentListener.showFragment(NoCardPayConstant.FASTBILL_LOGIN);
            }
        });
    }

    /**
     * 发送验证码
     */
    private void sendVerCode() {
        HashMap<String, Object> param = new HashMap<String, Object>();
        param.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(phone, 1, null));
        param.put(BaseProtocolKey.ACTION, "fastLogin");
        param.put(BaseProtocolKey.PHONE, SecureManager.getInstance().des(phone, 1, null));
        param.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        verfcodePresenter.getVerificationCode(param, VerificationCodeBean.class, false);
    }

    /**
     * 秒秒通登录
     */
    private void noCardPayLogin() {
        paramers.put(BaseProtocolKey.MOBILE, SecureManager.getInstance().des(phone, 1, null));
        paramers.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        paramers.put(BaseProtocolKey.ACTION, "fastLogin");
        paramers.put(BaseProtocolKey.VERIFYCODE, SecureManager.getInstance().des(verfcode, 1, null));
        hideSoftInput();
        mLognLoginPresenter.noCardPayLogin(paramers, Account.class, true);
    }

    @Override
    public void navigateToHome() {
        ClientEngine.getInstance().saveRMSData(BaseProtocolKey.NOCARDPAY_NAME, phone);
        mCountDownTimer.cancel();
        _mActivity.startActivity(new Intent(_mActivity, DelegateActivity.class));
        _mActivity.finish();
    }

    @Override
    public void loginError(String errorMsg) {
        mCountDownTimer.cancel();
        DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), errorMsg, false);
    }

    @Override
    public void showSendVerfCodeSuccess() {
        DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.send_verfcode_success));
    }


    @Override
    public void noSessionId() {
        DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), _mActivity.getString(R.string.login_fail), false, _mActivity.getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                _mActivity.finish();
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        paramers = new HashMap<>();
        mLognLoginPresenter = new AccountPresenterImpl(_mActivity);
        verfcodePresenter = new VerfcodePresenterImpl(_mActivity);
        verfcodePresenter.setSendVerfCodeView(this);
        mLognLoginPresenter.setmLoginView(this);
        perssionRequest = new PermissionRequest(_mActivity, this);

        PreferenceManager.getInstance(_mActivity).putBoolean("advertising", true);

        mCountDownTimer = new CountDownTimer(NoCardPayConstant.MILLISINFUTURE, NoCardPayConstant.COUNTDOWNINTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                mGetVerfcode.setText((millisUntilFinished / 1000) + _mActivity.getString(R.string.letter_getVefCode));
            }

            @Override
            public void onFinish() {
                resetVerfiyCode();
            }
        };
        String rmsData = ClientEngine.getInstance().getRMSData(BaseProtocolKey.NOCARDPAY_NAME);
        if (!TextUtils.isEmpty(rmsData)) {
            et_phone.setText(rmsData);
        }
    }

    /**
     * 重置按钮状态
     */
    private void resetVerfiyCode() {
        mGetVerfcode.setEnabled(true);
        mGetVerfcode.setText(_mActivity.getString(R.string.getvercode));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SETTING: {
                if (AndPermission.hasPermission(_mActivity, Permission.PHONE) && AndPermission.hasPermission(_mActivity, Permission.STORAGE)) {
                    noCardPayLogin();
                }
                break;
            }
        }
    }

    @Override
    public void permissionYes(List<String> permissions) {
        noCardPayLogin();
    }

    @Override
    public void permissionFail(List<String> permissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(_mActivity, permissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(NoCardLoginFragment.this, REQUEST_CODE_SETTING).show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLognLoginPresenter.onDestory();
    }
}
